<template>
  <div class="dict-type-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-header">
        <span class="search-title">搜索条件</span>
        <div class="search-actions">
          <!-- 收起按钮 -->
          <el-button 
            :icon="searchCollapsed ? ArrowDown : ArrowUp" 
            @click="toggleSearch"
            class="collapse-btn"
          >
            {{ searchCollapsed ? '展开' : '收起' }}
          </el-button>
          <!-- 刷新按钮 - 只刷新表格数据 -->
          <el-button 
            :icon="Refresh" 
            @click="refreshTable"
            class="refresh-btn"
          >
            刷新
          </el-button>
        </div>
      </div>
      
      <el-collapse-transition>
        <div v-show="!searchCollapsed">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true">
            <el-form-item label="字典名称：" prop="dictName">
              <el-input
                v-model="queryParams.dictName"
                placeholder="请输入字典名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="字典类型：" prop="dictType">
              <el-input
                v-model="queryParams.dictType"
                placeholder="请输入字典类型"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="字典状态：" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable
              style="width: 120px">
                <el-option label="所有" value="" />
                <el-option label="正常" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间：">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>字典类型列表</span>
          <div class="table-actions">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
             <el-button 
              type="danger" 
              :icon="Delete" 
              @click="handleBatchDelete"
              :disabled="multipleSelection.length === 0"
            >
              删除
            </el-button>
            <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
            <!-- 刷新缓存按钮 -->
            <el-button type="warning" :icon="RefreshRight" @click="handleRefreshCache">刷新缓存</el-button>
          </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="dictTypeList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="dictName" label="字典名称" min-width="120" />
        <el-table-column prop="dictType" label="字典类型" min-width="150">
          <template #default="scope">
            <el-link 
              type="primary" 
              :underline="false"
              @click="handleDictTypeClick(scope.row)"
              class="dict-type-link"
            >
              {{ scope.row.dictType }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(scope.row)"
            >修改</el-button>
            <el-button
              type="primary"
              link
              :icon="Search"
              @click="handleViewData(scope.row)"
            >数据</el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 对话框保持不变 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="formData.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="formData.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  Edit, 
  Delete, 
  ArrowDown, 
  ArrowUp,
  RefreshRight 
} from '@element-plus/icons-vue'
import { 
  getDictTypes, 
  addDictType, 
  updateDictType, 
  deleteDictType, 
  getDictTypeById,
  refreshCache as refreshCacheApi  
} from '@/api/dict'
import request from '@/utils/request'

const router = useRouter()

// 搜索区域折叠状态
const searchCollapsed = ref(false)

// 搜索表单
const queryParams = reactive({
  dictName: '',
  dictType: '',
  status: '',
  pageNumber: 1,
  pageSize: 10
})

const dateRange = ref([])

// 表格数据
const loading = ref(false)
const dictTypeList = ref([])
const total = ref(0)

// 多选数据
const multipleSelection = ref([])

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单数据
const formData = ref({
  dictId: undefined,
  dictName: '',
  dictType: '',
  status: '0',
  remark: ''
})

// 表单验证规则
const formRules = {
  dictName: [
    { required: true, message: '字典名称不能为空', trigger: 'blur' }
  ],
  dictType: [
    { required: true, message: '字典类型不能为空', trigger: 'blur' }
  ]
}

// 引用
const queryFormRef = ref()
const formRef = ref()

// 生命周期
onMounted(() => {
  getList()
})

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      startTime: dateRange.value?.[0] || null,
      endTime: dateRange.value?.[1] || null
    }
    
    const response = await getDictTypes(params)
    dictTypeList.value = response.items
    total.value = response.totalCount
  } catch (error) {
    console.error('获取字典类型列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 多选处理
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    const dictNames = multipleSelection.value.map(item => item.dictName).join('、')
    await ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条字典类型吗？包括：${dictNames}`, '提示', {
      type: 'warning'
    })
    
    // 逐个删除，后端没有批量删除接口
    const deletePromises = multipleSelection.value.map(item => 
      deleteDictType(item.dictId)
    )
    
    await Promise.all(deletePromises)
    ElMessage.success('批量删除成功')
    
    // 清空选择
    multipleSelection.value = []
    // 刷新列表
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 点击字典类型链接
const handleDictTypeClick = (row) => {
  router.push({
    path: '/dict/data',
    query: {
      dictType: row.dictType,
      dictName: row.dictName
    }
  })
}

// 切换搜索区域显示/隐藏
const toggleSearch = () => {
  searchCollapsed.value = !searchCollapsed.value
}

// 刷新表格数据 
const refreshTable = () => {
  getList()
  ElMessage.success('刷新成功')
}

// 刷新缓存方法
const handleRefreshCache = async () => {
  try {
    console.log('刷新缓存按钮被点击')
    
    await ElMessageBox.confirm('确认刷新缓存吗？这将清除所有字典缓存并重新加载数据。', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    console.log('调用刷新缓存API...')
    
    // 调用刷新缓存接口
    await refreshCacheApi()
    
    ElMessage.success('缓存刷新成功')
    console.log('缓存刷新成功')

    // 重新加载数据
    await getList()
    console.log('数据重新加载完成')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('缓存刷新失败:', error)
      ElMessage.error('缓存刷新失败: ' + (error.message || '未知错误'))
    } else {
      console.log('用户取消了缓存刷新')
    }
  }
}



// 搜索
const handleQuery = () => {
  queryParams.pageNumber = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  dateRange.value = []
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNumber = 1
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNumber = val
  getList()
}

// 新增
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增字典类型'
  formData.value = {
    dictId: undefined,
    dictName: '',
    dictType: '',
    status: '0',
    createBy: 'admin',
    createTime: null,
    updateBy: 'admin',
    updateTime: null,
    remark: ''
  }
}

// 修改
const handleEdit = async (row) => {
  try {
    loading.value = true
    const fullData = await getDictTypeById(row.dictId)
    
    dialog.visible = true
    dialog.title = '修改字典类型'
    formData.value = { 
      ...fullData,
      updateBy: 'admin',
      updateTime: new Date().toISOString()
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 查看字典数据
const handleViewData = (row) => {
  router.push({
    path: '/dict/data',
    query: {
      dictType: row.dictType,
      dictName: row.dictName
    }
  })
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除字典类型"${row.dictName}"吗？`, '提示', {
      type: 'warning'
    })
    
    await deleteDictType(row.dictId)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate()
  
  try {
    const currentTime = new Date().toISOString()
    
    let submitData = {
      dictId: formData.value.dictId,
      dictName: formData.value.dictName,
      dictType: formData.value.dictType,
      status: formData.value.status,
      remark: formData.value.remark,
      createBy: formData.value.createBy || 'admin',
      createTime: formData.value.createTime || currentTime,
      updateBy: 'admin',
      updateTime: currentTime,
      dictDatas: formData.value.dictDatas || []
    }
    
    if (submitData.dictId) {
      const fullData = await getDictTypeById(submitData.dictId)
      
      submitData = {
        ...fullData,
        ...submitData,
        updateBy: 'admin',
        updateTime: currentTime
      }
      
      await updateDictType(submitData)
      ElMessage.success('修改成功')
    } else {
      submitData.createBy = 'admin'
      submitData.createTime = currentTime
      submitData.updateBy = 'admin'
      submitData.updateTime = currentTime
      submitData.dictDatas = []
      
      await addDictType(submitData)
      ElMessage.success('新增成功')
    }
    
    dialog.visible = false
    getList()
  } catch (error) {
    ElMessage.error(error.response?.data || '操作失败')
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
.dict-type-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 20px;
  background: white;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.search-title {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.search-actions {
  display: flex;
  gap: 8px;
}

/* 收起按钮样式 */
.collapse-btn {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.collapse-btn:hover {
  background-color: #ecf5ff;
  border-color: #c6e2ff;
  color: #409eff;
}

/* 刷新按钮样式 */
.refresh-btn {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.refresh-btn:hover {
  background-color: #f0f9ff;
  border-color: #c6e2ff;
  color: #409eff;
}

.table-card {
  margin-bottom: 20px;
  background: white;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 字典类型链接样式 */
.dict-type-link {
  font-weight: 500;
  cursor: pointer;
}

.dict-type-link:hover {
  color: #409eff;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form :deep(.el-form-item) {
    width: 100% !important;
    margin-bottom: 10px;
  }

  .search-form :deep(.el-input),
  .search-form :deep(.el-select),
  .search-form :deep(.el-date-picker) {
    width: 100% !important;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .table-actions {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>